package com.sias.reflection.class_;

import com.sias.Cat;

import java.lang.reflect.Field;

/**
 * @author 吴文杰
 * @version 1.0
 * @createTime 2023-05-02 13:10:44
 */
@SuppressWarnings("all")
public class Class01 {
  public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchFieldException {
    /*  传统new对象
         public Class<?> loadClass(String name) throws ClassNotFoundException {
            return loadClass(name, false);
         }
     */
    // Cat cat = new Cat();
    Class<?> cls = Class.forName("com.sias.Cat");
    System.out.println(cls);//显示cls对象，是哪个类的Class对象 class com.sias.Cat
    System.out.println(cls.getClass());//输出cls运行类型 class java.lang.Class
    System.out.println(cls.getPackage());//获取包名 package com.sias
    System.out.println(cls.getName());//获取全类名 com.sias.Cat
    Cat cat = (Cat) cls.newInstance();//通过cls创建实例对象 com.sias.Cat@1b6d3586
    System.out.println(cat);//cat.toString()
    System.out.println(cat.age);//20
    Field age = cls.getField("age");//不能获取私有属性
    System.out.println(age.get(cat));//20
    age.set(cat,5);//通过反射给属性赋值
    System.out.println(age.get(cat));//5
    Field[] fields = cls.getFields();
    System.out.println("=======所有字段名=======");
    for (Field field : fields) {
      System.out.println("字段名:"+field.getName()+"\tvalue:"+field.get(cat));//字段名+字段值
    }
  }
}
